<?php

namespace services\clinic;

use Yii;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\member\Attr;
use common\models\member\Member;
use common\models\clinic\Clinic;
use common\models\clinic\RelationKefu;
use common\models\base\Profession;
use api\modules\v1\forms\clinic\RelationKefuForm;

/**
 * Class RelationKefuService
 * @package services\clinic
 */
class RelationKefuService extends Service
{
    /**
     * 根据ID查找诊室信息
     *
     * @param int $id
     * @return RelationKefu|null
     */
    public function findById(int $id = 0): ?RelationKefu
    {
        return RelationKefu::find()->where(['id' => $id])->one();
    }

    /**
     * 查找诊室信息
     *
     * @param array $condition
     * @return RelationKefu|null
     */
    public function findInfo(array $condition = []): ?RelationKefu
    {
        $query = RelationKefu::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = RelationKefu::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['kefu_id']) && $query->andWhere(['kefu_id' => $condition['kefu_id']]);
        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);

        // indexBy
        isset($condition['indexBy']) && $query->indexBy($condition['indexBy']);

        return $query->asArray()->all();
    }

    /**
     * 业务设置列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0)
    {
        $query = Member::find()->alias('a')
            ->select([
                'a.id', 'a.realname',
                'GROUP_CONCAT(d.name) AS clinic_name'
            ])
            ->innerJoin(Attr::tableName().' AS b', 'b.member_id = a.id AND b.project_id = '.$params['project_id'])
            ->leftJoin(RelationKefu::tableName().' AS c', 'c.kefu_id = a.id AND c.project_id = '.$params['project_id'])
            ->leftJoin(Clinic::tableName().' AS d', 'd.id = c.clinic_id')
            ->groupBy('a.id');

        $query->andWhere(['b.profession_id' => [Profession::ID_CUSTOMER_LEADER, Profession::ID_CUSTOMER]]);

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query
            ->orderBy(['a.id' => SORT_ASC])
            ->asArray()
            ->all();

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];
    }

    /**
     * 格式化列表数据
     *
     * @param array $data
     * @return array
     */
    public function getListPageFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $clinicNameArr = $row['clinic_name'] ? explode(',', $row['clinic_name']) : [];
            $list[] = [
                'id' => $row['id'],
                'realname' => $row['realname'],
                'clinic_name_arr' => $clinicNameArr,
            ];
        }

        return $list;
    }

    /**
     * 编辑客服绑定诊室
     *
     * @param RelationKefuForm $model
     * @return array|mixed
     */
    public function edit(RelationKefuForm $model)
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.删除绑定诊室
            RelationKefu::deleteAll([
                'kefu_id' => $model->kefu_id,
                'project_id' => $model->project_id,
                'clinic_id' => $model->getDeleteClinicIds(),
            ]);

            // 2.添加绑定诊室【诊室改为不必填】
            if ($model->getAddClinicIds()) {
                foreach ($model->getAddClinicIds() as $row) {
                    $relationKefu = new RelationKefu();
                    $relationKefu->project_id = $model->project_id;
                    $relationKefu->kefu_id = $model->kefu_id;
                    $relationKefu->clinic_id = $row;
                    $relationKefu->created_at = Yii::$app->params['time'];
                    $relationKefu->save();
                }
            }

            $transaction->commit();

            return ['kefu_id' => $model->kefu_id];
        } catch (\Exception $e) {
            $transaction->rollBack();

            return CommonHelper::api(422, $e->getMessage());
        }
    }
}
